/*
 * @Author: ischen.x ischen.x@foxmail.com
 * @Date: 2025-01-03 14:51:37
 * @LastEditors: ischen.x ischen.x@foxmail.com
 * @LastEditTime: 2025-03-05 15:36:20
 * 
 * Copyright (c) 2025 by fhchengz, All Rights Reserved. 
 */
#ifndef __TLV_H
#define __TLV_H

#include <stdint.h>
#include <stdlib.h>

/* ---------- 用户可配置区域 ---------- */
typedef uint16_t head_type;
typedef uint8_t tag_type;
typedef uint8_t length_type;
typedef uint8_t value_type;
typedef uint8_t crc_type;
/* ----------------------------------- */

// 错误代码宏定义
#define TLV_PACK_SUCCESS    0    // 成功
#define TLV_PACK_ERR_MEMORY -1   // 内存分配失败
#define TLV_PACK_ERR_NULL   -2   // 空指针错误
#define TLV_PACK_ERR_CRC    -3   // CRC 计算失败

typedef int (*tlv_crc_t)(uint8_t *data, uint8_t len);

typedef struct _tlv {
    head_type head;            
    tag_type tag;              
    length_type length;        
    value_type *value;         
    crc_type crc;              
} tlv_frame_t;

typedef enum {
    STATE_SEARCH_HEADER,
    STATE_READ_TAG,
    STATE_READ_LENGTH,
    STATE_READ_DATA,
    STATE_READ_CRC
} ParserState;

int tlv_set_crc_function(tlv_crc_t tlv_fun);
int tlv_pack(head_type head, tag_type tag, uint8_t *value, length_type value_len, uint8_t **output_buffer, uint8_t *out_len);
int tlv_unpack(uint8_t data_in, tlv_frame_t **fream_out);
int tlv_free(tlv_frame_t *frame);

#endif /* __TLV_H */